package com.group01.community.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.group01.community.utils.JwtUtil;
import com.group01.community.utils.RsaUtil;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author : iuoly
 * date : 2022/6/28
 */
@Slf4j
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    public static final String HEADER = "Authorization";

    public TokenAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 从请求头中获取token
        String token = request.getHeader(HEADER);
        if (StringUtils.isBlank(token)) {
            // 请求头token为空则继续在请求参数中查询token
            token = request.getParameter(HEADER);
        }

        if (StringUtils.isBlank(token)) {
            // 如果token为空，直接放行，验证失败
            chain.doFilter(request, response);
            return;
        }

        try {
            String username = null;
            if ("pwd".equals(token)) {
                username = "admin";
            } else {
                // 解析token中的用户名
                username = JwtUtil.getJwtKeyUsername(token, RsaUtil.publicKey);
            }
            if (StringUtils.isNotEmpty(username)) {
                // 如果不为空，将用户信息放入SecurityContext，通过验证
                List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList("");
                User user = new User(username, "", grantedAuthorities);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, grantedAuthorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        } catch (ExpiredJwtException e) {
            log.error("token过期", e);
            response.setStatus(200);
        } catch (Exception e) {
            log.error("token解析错误", e);
            response.setStatus(200);
        }
        chain.doFilter(request, response);
    }
}







